init('AutoCompleteResponse');
(function(){
	var Collections = require('Collections'),
    StringUtils = require('StringUtils');

	var gcs     = Collections.gcs,
		filter  = Collections.filter,
		iterate = Collections.iterate,
		List    = Collections.List,
		format  = StringUtils.format;
	
	var AutoCompleteResponse = function(id, results){
		this.results = results;
		this.values  = [];
		var bases    = [];
		var list     = this.values;
		var count    = 0;
		
		id = StringUtils.trimQuote( id );
		
		iterate(results, function(set){
			var filtered = filter(set.values, '^' + id, set._toString);
			List.addAll(list, filtered);
			var base = gcs(filtered, set._toString);
			if( base )
				bases.push(base);
			if( set.values )
				count += set.values.length;
		}, this);
		if( bases.length == 1 && count != 1 && !id ){
			this.base = '';
		}else{
			this.base = gcs(bases);
			if( this.base.match(/.* .*/) )
				this.base = "'" + this.base + "'";
		}
		this.toHTML = function(){
			var html = '';
			iterate(results, function(set){
				var filtered = filter(set.values, '^' + id, set._toString);
				iterate(filtered, function(item){
					if( !set.toHTML ) set.toHTML = "${0} ";
					html += format(set.toHTML, item);
				});
			});
			return html;
		};
	};

	exports.create =function(){ 
		return new AutoCompleteResponse(); 
	};
	exports.ctor = AutoCompleteResponse;
})();